using System.Collections.Generic;
using System.IO;
using System.Linq;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

namespace MailMerge.Infrastructure
{
	public static class WordprocessingDocumentExtensions
	{
		public static IEnumerable<ContentControlInfo> GetContentControls(this WordprocessingDocument doc)
		{
			var rootElement = doc.MainDocumentPart.Document;

			var contentControls = from sdt in rootElement.Descendants<OpenXmlCompositeElement>()
								  let properties = sdt.GetFirstChild<SdtProperties>()
								  let content = sdt.GetFirstChild<SdtContentBlock>()
								  where properties != null
								  select new ContentControlInfo(sdt);

			return contentControls;
		}

		public static void ReplaceContent(this OpenXmlElement placeholder, string pathToContent, string altChunkId)
		{
			var doc = placeholder.Ancestors<Document>().Single();
			var altChunk = GetAltChunk(doc, altChunkId, pathToContent);
			placeholder.InsertAfterSelf(altChunk);
		}

		private static AltChunk GetAltChunk(Document doc, string altChunkId, string pathToContent)
		{
			var mainPart = doc.MainDocumentPart;
			var chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);
			var smith = new object();
			lock (smith)
				using (var fs = File.OpenRead(pathToContent))
					chunk.FeedData(fs);

			var altChunk = new AltChunk() { Id = altChunkId };
			altChunk
				.AppendChild(new AltChunkProperties())
				.AppendChild(new MatchSource() { Val = true });
			return altChunk;
		}

	}
}